package com.withouther.robot.rainingrobot.util.ai.tts;

import cn.hutool.setting.dialect.Props;
import com.withouther.robot.rainingrobot.core.constants.AsrType;
import com.withouther.robot.rainingrobot.util.ai.tts.ali.TTSAudioALY;
import com.withouther.robot.rainingrobot.util.ai.tts.model.TTSParam;
import com.withouther.robot.rainingrobot.util.ai.tts.model.TTSResult;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TTSAudioFactory
 * @Auther: tzq
 * @Date: 2020/9/24 14:00
 * @Description:
 */
@Slf4j
public class TTSAudioFactory {

    private static TTSAudioFactory tools = null;

    private static Map<Integer, TTSAudio> ttsMap = new HashMap<>();

    /**
     * 阿里云TTS
     */
    public static final int alyTTS = 1;

    static {
        ttsMap.put(alyTTS, new TTSAudioALY());
    }

    private TTSAudioFactory() {
        init();
    }

    /**
     * 该类的初始化方法
     */
    public void init() {

    }

    /**
     * 重置该类
     */
    public void reset() {
        init();
    }

    /**
     * 工厂方法，返回
     *
     * @return
     */
    public static TTSAudioFactory getFactory() {
        if (tools == null) {
            create();
        }
        return tools;
    }

    /**
     * 线程安全的创建方法，防止并发多次创建
     */
    private static synchronized void create() {
        if (tools == null) {
            tools = new TTSAudioFactory();
        }
    }

    public TTSResult ttsAction(TTSParam ttsParam, int type) throws Exception {
        TTSAudio ttsAudio = ttsMap.get(type);
        String ttsPath = new Props("config.properties").getStr("tts.file.path");
        String filePath = ttsPath + "/" + ttsParam.getText()  + ".wav";
        File file = new File(filePath);
        if (!file.exists()) {
            ttsParam.setFilePath(filePath);
            log.info("Create the TTS file text:{}", ttsParam.getText());
            return ttsAudio.textToAudio(ttsParam);
        }
        TTSResult ttsResult = new TTSResult();
        ttsResult.setFilePath(filePath);
        return ttsResult;
    }
}
